package net.qqxh.controller;

import net.qqxh.common.utils.FileAnalysisTool;
import net.qqxh.common.utils.SvnUtil;
import net.qqxh.handler.SvnCheckOutHandler;
import net.qqxh.handler.SvnUpdateHandler;
import net.qqxh.persistent.JfUserSimple;
import net.qqxh.persistent.SearchLib;
import net.qqxh.service.FileService;
import net.qqxh.service.task.FileResolveTask;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.wc.ISVNOptions;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

import java.io.File;


@RestController
@RequestMapping("/remoteRepository")
public class RemoteRepositoryController extends BaseController {
    private static Boolean inWorkingState=false;
    @Autowired
    private FileResolveTask fileResolveTask;
    @Autowired
    private FileService fileService;
    @Value("${SUPPORT_EXTENSIONS}")
    private String[] supportExtensions;
    @RequestMapping("/update")
    public Object update(@RequestParam(name = "path") String path) {
        JfUserSimple jfUserSimple = getLoginUser();
        SearchLib searchLib = jfUserSimple.getSearchLib();
        if (StringUtils.isEmpty(searchLib.getSvnRepository_url())) {
            return responseJsonFactory.getSuccessJson("更新失败，未配置svn仓库地址", "");
        }
        if(!StringUtils.equals(searchLib.getRemoteRepositoryMode(),"svn")){
            return responseJsonFactory.getErrorJson("error未启用，svn管理", "");
        }
        if(inWorkingState){
            return responseJsonFactory.getErrorJson("error后台任务尚未执行完毕，请稍后操作...", "");
        }
        inWorkingState=true;
        SVNRepositoryFactoryImpl.setup();
        //相关变量赋值
        ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
        SVNClientManager ourClientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, searchLib.getSvnUsername(), searchLib.getSvnPassword());
        File wcDir = new File(path);
        long workingVersion = -1;
        try {
            boolean isworkcopy = SvnUtil.isWorkingCopy(wcDir);
            if (!isworkcopy) {
                checkout();
            }
            workingVersion = SvnUtil.update(ourClientManager, wcDir, SVNRevision.HEAD, SVNDepth.INFINITY,  getSvnUpdateHandler(searchLib));
        } catch (Exception e) {
            e.printStackTrace();
            return responseJsonFactory.getErrorJson("更新失败", "");
        }

        return responseJsonFactory.getSuccessJson("更新成功", "");
    }

    @RequestMapping("/checkout")
    public Object checkout() {
        JfUserSimple jfUserSimple = getLoginUser();
        SearchLib searchLib = jfUserSimple.getSearchLib();
        if(!StringUtils.equals(searchLib.getRemoteRepositoryMode(),"svn")){
            return responseJsonFactory.getErrorJson("error未启用，svn管理", "");
        }
        if (StringUtils.isEmpty(searchLib.getSvnRepository_url())) {
            return responseJsonFactory.getSuccessJson("更新失败，未配置svn仓库地址", "");
        }
        if(inWorkingState){
            return responseJsonFactory.getErrorJson("error后台任务尚未执行完毕，请稍后操作...", "");
        }
        inWorkingState=true;

        SVNRepositoryFactoryImpl.setup();
        //相关变量赋值
        SVNURL repositoryURL = null;
        try {
            repositoryURL = SVNURL.parseURIEncoded(searchLib.getSvnRepository_url());
        } catch (Exception e) {
            //
        }
        ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
        SVNClientManager ourClientManager = SVNClientManager.newInstance(
                (DefaultSVNOptions) options, searchLib.getSvnUsername(), searchLib.getSvnPassword());
        //要把版本库的内容check out到的目录
        File wcDir = new File(searchLib.getFileSourceDir());
        if (!wcDir.exists()) {
            wcDir.mkdir();
        }
        long workingVersion = -1;

        try {
            if (SvnUtil.isWorkingCopy(wcDir)) {
                SvnUtil.doCleanup(ourClientManager, wcDir);
                workingVersion = SvnUtil.update(ourClientManager, wcDir, SVNRevision.HEAD, SVNDepth.INFINITY, getSvnUpdateHandler(searchLib));
            } else {
                SvnCheckOutHandler svnCheckOutHandler=new SvnCheckOutHandler(()->{
                    inWorkingState=false;
                    fileService.resolveFliesList2TreeNode();
                });
                workingVersion = SvnUtil.checkout(ourClientManager, repositoryURL, SVNRevision.HEAD, wcDir, SVNDepth.INFINITY, svnCheckOutHandler);

            }

        } catch (Exception e) {
            e.printStackTrace();
            inWorkingState=false;
            return responseJsonFactory.getErrorJson("检出失败", "");
        }
        return responseJsonFactory.getSuccessJson("更新成功", "");
    }

    private SvnUpdateHandler getSvnUpdateHandler( SearchLib searchLib){
        SvnUpdateHandler svnUpdateHandler = new SvnUpdateHandler(()->{
            inWorkingState=false;
            fileService.resolveFliesList2TreeNode();
        });
        svnUpdateHandler.setFileFilter(FileAnalysisTool.getIOFileFilter(supportExtensions));
        svnUpdateHandler.setSearchLib(searchLib);
        svnUpdateHandler.setFileResolveTaskCallBack(null);
        svnUpdateHandler.setFileResolveTask(fileResolveTask);
        return svnUpdateHandler;

    }
    @RequestMapping("/commit")
    public Object commit() {
        JfUserSimple jfUserSimple = getLoginUser();
        SearchLib searchLib = jfUserSimple.getSearchLib();
        if(!StringUtils.equals(searchLib.getRemoteRepositoryMode(),"svn")){
            return responseJsonFactory.getErrorJson("error未启用，svn管理", "");
        }
        SVNRepositoryFactoryImpl.setup();
        //相关变量赋值
        SVNURL repositoryURL = null;
        try {
            repositoryURL = SVNURL.parseURIEncoded(searchLib.getSvnRepository_url());
        } catch (Exception e) {

        }
        ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
        SVNClientManager ourClientManager = SVNClientManager.newInstance(
                (DefaultSVNOptions) options, searchLib.getSvnUsername(), searchLib.getSvnPassword());
        //要把版本库的内容check out到的目录
        File wcDir = new File(searchLib.getFileSourceDir());
        try {
            SvnUtil.addEntry(ourClientManager, wcDir);
            SvnUtil.commit(ourClientManager, wcDir, false, "通过jfile提交");
        } catch (Exception e) {
            e.printStackTrace();
            return responseJsonFactory.getErrorJson("提交失败", "");
        }
        return responseJsonFactory.getSuccessJson("提交成功", "");
    }
}
